package com.jack.xiaoer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jack.xiaoer.constant.CategoryTypeEnum;
import com.jack.xiaoer.constant.MyConstant;
import com.jack.xiaoer.dao.CategoryMapper;
import com.jack.xiaoer.entity.Category;
import com.jack.xiaoer.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/10.
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    private final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category createCategory(Optional<Category> category) {
        if (!category.isPresent()) return null;
        final Category cate = category.get();
        cate.setGmtCreate(Instant.now());
        cate.setGmtModified(Instant.now());

        int row = categoryMapper.insert(cate);

        if (row > 0) {
            return cate;
        }
        return null;
    }

    @Override
    public IPage<Category> listTopCategory(Integer pageNum, Integer pageSize) {

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", MyConstant.TOP_CATEGORY_ID);
        queryWrapper.eq("type", CategoryTypeEnum.SYSTEM.getCode());
        queryWrapper.eq("deleted", MyConstant.UNDELETED);
        queryWrapper.orderByAsc("sort_order");
        Page<Category> page = new Page<>(pageNum, pageSize);

        IPage<Category> categoryPage = categoryMapper.selectPage(page, queryWrapper);
        return categoryPage;
    }

}
